import React, { useState, useRef } from 'react';
import styles from './ColorExtractor.module.css';

const ColorExtractor = () => {
    const [colors, setColors] = useState({
        top: null,
        right: null,
        bottom: null,
        left: null,
        center: null
    });
    const [imageUrl, setImageUrl] = useState('');
    const [gradientDirection, setGradientDirection] = useState('to bottom'); // 添加渐变方向状态
    const canvasRef = useRef(null);

    const handleImageUpload = (e) => {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = () => {
                setImageUrl(reader.result);
            };
            reader.readAsDataURL(file);
        }
    };

    const getPixelColor = (ctx, x, y) => {
        const pixel = ctx.getImageData(x, y, 1, 1).data;
        return {
            r: pixel[0],
            g: pixel[1],
            b: pixel[2]
        };
    };

    const rgbToHex = ({ r, g, b }) => {
        return '#' + [r, g, b].map(x => {
            const hex = x.toString(16);
            return hex.length === 1 ? '0' + hex : hex;
        }).join('');
    };

    const extractColors = (img) => {
        const canvas = canvasRef.current;
        const ctx = canvas.getContext('2d');
        
        // 设置 canvas 大小与图片一致
        canvas.width = img.width;
        canvas.height = img.height;
        
        // 在 canvas 上绘制图片
        ctx.drawImage(img, 0, 0);

        // 获取五个位置的颜色
        const positions = {
            top: { x: Math.floor(img.width / 2), y: 0 },
            right: { x: img.width - 1, y: Math.floor(img.height / 2) },
            bottom: { x: Math.floor(img.width / 2), y: img.height - 1 },
            left: { x: 0, y: Math.floor(img.height / 2) },
            center: { x: Math.floor(img.width / 2), y: Math.floor(img.height / 2) }
        };

        const extractedColors = {};
        for (const [position, coords] of Object.entries(positions)) {
            extractedColors[position] = getPixelColor(ctx, coords.x, coords.y);
        }

        setColors(extractedColors);
    };

    // 添加方向映射函数
    const getGradientColors = () => {
        if (!colors.top) return [];
        
        const directionMap = {
            'to bottom': ['top', 'center', 'bottom'],
            'to right': ['left', 'center', 'right'],
            'to top': ['bottom', 'center', 'top'],
            'to left': ['right', 'center', 'left'],
        };

        return directionMap[gradientDirection].map(pos => colors[pos]).filter(Boolean);
    };

    // 生成CSS代码
    const generateGradientCSS = () => {
        const gradientColors = getGradientColors();
        if (gradientColors.length === 0) return '';

        const colorStops = gradientColors.map((color, index) => {
            const percentage = index * (100 / (gradientColors.length - 1));
            return `rgb(${color.r}, ${color.g}, ${color.b}) ${percentage}%`;
        });

        return `background: linear-gradient(${gradientDirection}, ${colorStops.join(', ')});`;
    };

    // 复制CSS代码
    const copyToClipboard = (text) => {
        navigator.clipboard.writeText(text)
            .then(() => alert('CSS代码已复制到剪贴板！'))
            .catch(err => console.error('复制失败：', err));
    };

    return (
        <div className={styles.container}>
            <span className={styles.title}>在ui设计网站有很多好看的界面设计，但是他只有一张静态图没有切图，所以用这个工具来提取渐变色</span>
            <canvas ref={canvasRef} style={{ display: 'none' }} />
            <input 
                type="file" 
                accept="image/*" 
                onChange={handleImageUpload}
                className={styles.fileInput}
            />
            
            {imageUrl && (
                <>
                    <div className={styles.imageContainer}>
                        <img
                            src={imageUrl}
                            onLoad={(e) => extractColors(e.target)}
                            className={styles.previewImage}
                        />
                    </div>
                    
                    {/* 添加方向控制 */}
                    <div className={styles.controls}>
                        <label>渐变方向：</label>
                        <select 
                            value={gradientDirection}
                            onChange={(e) => setGradientDirection(e.target.value)}
                            className={styles.select}
                        >
                            <option value="to bottom">从上到下</option>
                            <option value="to right">从左到右</option>
                            <option value="to top">从下到上</option>
                            <option value="to left">从右到左</option>
                        </select>
                    </div>

                    {/* 渐变色预览 */}
                    <div className={styles.gradientPreview}>
                        <div 
                            className={styles.gradientBox}
                            style={{ background: `linear-gradient(${gradientDirection}, ${getGradientColors()
                                .map(c => `rgb(${c.r}, ${c.g}, ${c.b})`)
                                .join(', ')})` 
                            }}
                        />
                    </div>

                    {/* CSS代码展示 */}
                    <div className={styles.cssCode}>
                        <pre>{generateGradientCSS()}</pre>
                        <button 
                            onClick={() => copyToClipboard(generateGradientCSS())}
                            className={styles.copyButton}
                        >
                            复制CSS
                        </button>
                    </div>

                    <div className={styles.colorPalette}>
                        {Object.entries(colors).map(([position, color]) => (
                            <div key={position} className={styles.colorItem}>
                                <div 
                                    className={styles.colorBox}
                                    style={{ 
                                        backgroundColor: color ? 
                                            `rgb(${color.r},${color.g},${color.b})` : 
                                            '#fff'
                                    }}
                                />
                                <span className={styles.colorPosition}>{position}</span>
                                <span className={styles.colorCode}>
                                    {color ? rgbToHex(color) : ''}
                                </span>
                            </div>
                        ))}
                    </div>
                </>
            )}
        </div>
    );
};

export default ColorExtractor;